import org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// UpdateBook类继承HttpServlet，用于处理修改指定书号的图书信息
@WebServlet("/update_book")
public class UpdateBook extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 数据库连接相关配置信息
    private static final String URL = "jdbc:mysql://localhost:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";

    // 根据图书编号、名称和作者信息在数据库中更新图书信息
    public JSONObject updateBook(String bookNumber, String bookName, String bookAuthor) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 加载驱动
             Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            connection = DriverManager.getConnection(URL, USER, PASSWORD);

            // 编写更新图书的SQL语句，使用预编译防止SQL注入（字段有number、name、author）
            String sqlUpdate = "UPDATE t_book SET name =?, author =? WHERE number =?";
            preparedStatement = connection.prepareStatement(sqlUpdate);
            preparedStatement.setString(1, bookName);
            preparedStatement.setString(2, bookAuthor);
            preparedStatement.setString(3, bookNumber);

            // 执行更新操作，返回受影响的行数，大于0表示更新成功
             int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                // 更新成功后，查询更新后的图书信息
                String sqlSelect = "SELECT * FROM t_book WHERE number =? AND name =? AND author =?";
                preparedStatement = connection.prepareStatement(sqlSelect);
                preparedStatement.setString(1, bookNumber);
                preparedStatement.setString(2, bookName);
                preparedStatement.setString(3, bookAuthor);
                resultSet = preparedStatement.executeQuery();
                if (resultSet.next()) {
                    JSONObject updatedBook = new JSONObject();
                    updatedBook.put("number", resultSet.getString("number"));
                    updatedBook.put("name", resultSet.getString("name"));
                    updatedBook.put("author", resultSet.getString("author"));
                     return updatedBook;
                }else {
                // 如果没有查询到符合条件的更新后记录，记录日志或者抛出异常
                System.err.println("更新图书成功，但查询更新后记录失败，可能存在数据不一致问题");
                return null;
            }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭数据库相关资源
              try {
                if (resultSet!= null) {
                    resultSet.close();
                }
                if (preparedStatement!= null) {
                    preparedStatement.close();
                }
                if (connection!= null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 处理GET请求，根据传入的图书相关信息修改图书并返回相应结果给客户端
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置跨域请求相关头信息
         response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        // 设置响应内容类型为JSON格式
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取要修改图书的编号（从请求参数中获取）
         String bookNumber = request.getParameter("number");
        String bookName = request.getParameter("name");
        String bookAuthor = request.getParameter("author");

        // 参数验证，如果必要参数有空值，返回错误信息
         if (bookNumber == null || bookNumber.isEmpty() || bookName == null || bookName.isEmpty() || bookAuthor == null || bookAuthor.isEmpty()) {
            JSONObject errorJson = new JSONObject();
            errorJson.put("error", "图书编号、名称和作者不能为空");
            out.println(errorJson.toString());
            out.close();
            return;
        }

        JSONObject resultJson = updateBook(bookNumber, bookName, bookAuthor);
        if (resultJson!= null) {
                response.getWriter().println(resultJson.toString());
        } else {
            JSONObject errorJson = new JSONObject();
            errorJson.put("error", "图书更新失败");
            response.getWriter().println(errorJson.toString());
            }
            
  
            out.close();
     }
}            
